#include "ipv4propertydialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QFont>
#include <QSpacerItem>
#include <QButtonGroup>
#include <QSizePolicy>
#include <QGridLayout>
#include <QProcess>
#include <QRegularExpression>
#include <QDebug> // Added for debugging
#include <QMessageBox>
#include <cstdio>
#include <QEvent>
#include "advanceddialog.h"

IPv4PropertyDialog::IPv4PropertyDialog(const ConnectionInfo &connInfo, const DeviceInfo &devInfo, QWidget *parent)
    : QDialog(parent), m_connInfo(connInfo), m_devInfo(devInfo)
{
    setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint);
    // setWindowFlags((windowFlags() & ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint) | Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    setWindowTitle("Internet 协议版本 4 (TCP/IPv4) 属性");
    setFixedWidth(479);
    // setFixedSize(this->size());
    // setFixedSize(479, 588); // 让窗口高度自适应
    QFont labelFont("Microsoft YaHei UI", 9);
    QFont boldFont("Microsoft YaHei UI", 9, QFont::Bold);
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(12, 16, 12, 12);
    mainLayout->setSpacing(16);

    // 描述文本
    QLabel *desc = new QLabel("如果网络支持此功能，则可以获取自动指派的IP设置。否则，你需要从网络系统管理员处获得适当的IP设置。", this);
    desc->setWordWrap(true);
    desc->setFont(labelFont);
    mainLayout->addWidget(desc);

    // --- 统一网格布局 ---
    QGridLayout *grid = new QGridLayout;
    grid->setHorizontalSpacing(32);
    grid->setVerticalSpacing(12);
    int row = 0;
    // IP部分
    radioAutoIP = new QRadioButton("自动获得IP地址(O)", this);
    radioManualIP = new QRadioButton("使用下面的IP地址(S):", this);
    radioAutoIP->setFont(labelFont);
    radioManualIP->setFont(labelFont);
    radioAutoIP->setFixedHeight(24);
    radioManualIP->setFixedHeight(24);
    QButtonGroup *ipBtnGroup = new QButtonGroup(this);
    ipBtnGroup->addButton(radioAutoIP);
    ipBtnGroup->addButton(radioManualIP);
    grid->addWidget(radioAutoIP, row++, 0, 1, 2);
    grid->addWidget(radioManualIP, row++, 0, 1, 2);
    QLabel *labelIP = new QLabel("IP地址(I):", this); labelIP->setFont(labelFont);
    QLabel *labelMask = new QLabel("子网掩码(U):", this); labelMask->setFont(labelFont);
    QLabel *labelGW = new QLabel("默认网关(D):", this); labelGW->setFont(labelFont);
    editIP = new QLineEdit(this);
    editMask = new QLineEdit(this);
    editGW = new QLineEdit(this);
    editIP->setFixedSize(200, 24);
    editMask->setFixedSize(200, 24);
    editGW->setFixedSize(200, 24);
    editIP->setFont(labelFont);
    editMask->setFont(labelFont);
    editGW->setFont(labelFont);
    QString editQss = "QLineEdit { border: 1px solid #A0A0A0; border-radius: 2px; background: white; }"
                      "QLineEdit:disabled { background: #F0F0F0; color: #A0A0A0; }";
    editIP->setStyleSheet(editQss);
    editMask->setStyleSheet(editQss);
    editGW->setStyleSheet(editQss);
    // 修复：为editMask安装事件过滤器，实现自动填充
    editMask->installEventFilter(this);
    grid->addWidget(labelIP, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
    grid->addWidget(editIP, row++, 1, Qt::AlignRight);
    grid->addWidget(labelMask, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
    grid->addWidget(editMask, row++, 1, Qt::AlignRight);
    grid->addWidget(labelGW, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
    grid->addWidget(editGW, row++, 1, Qt::AlignRight);
    // DNS部分
    radioAutoDNS = new QRadioButton("自动获得DNS服务器地址(B)", this);
    radioManualDNS = new QRadioButton("使用下面的DNS服务器地址(E):", this);
    radioAutoDNS->setFont(labelFont);
    radioManualDNS->setFont(labelFont);
    radioAutoDNS->setFixedHeight(24);
    radioManualDNS->setFixedHeight(24);
    // --- DNS单选框互斥组 ---
    QButtonGroup *dnsGroup = new QButtonGroup(this);
    dnsGroup->addButton(radioAutoDNS);
    dnsGroup->addButton(radioManualDNS);
    grid->addWidget(radioAutoDNS, row++, 0, 1, 2);
    grid->addWidget(radioManualDNS, row++, 0, 1, 2);
    QLabel *labelDNS1 = new QLabel("首选DNS服务器(P):", this); labelDNS1->setFont(labelFont);
    QLabel *labelDNS2 = new QLabel("备用DNS服务器(A):", this); labelDNS2->setFont(labelFont);
    editDNS1 = new DnsLineEdit(this);
    editDNS2 = new DnsLineEdit(this);
    editDNS1->setFixedSize(200, 24);
    editDNS2->setFixedSize(200, 24);
    editDNS1->setFont(labelFont);
    editDNS2->setFont(labelFont);
    editDNS1->setStyleSheet(editQss);
    editDNS2->setStyleSheet(editQss);
    grid->addWidget(labelDNS1, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
    grid->addWidget(editDNS1, row++, 1, Qt::AlignRight);
    grid->addWidget(labelDNS2, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
    grid->addWidget(editDNS2, row++, 1, Qt::AlignRight);
    // DNS优先级
    QLabel *labelDnsPriority = new QLabel("DNS优先级:", this); labelDnsPriority->setFont(labelFont);
    comboDnsPriority = new QComboBox(this);
    comboDnsPriority->addItem("高（优先使用此DNS）"); // 0
    comboDnsPriority->addItem("中（一般推荐）");     // 1
    comboDnsPriority->addItem("低（不优先）");       // 2
    comboDnsPriority->setCurrentIndex(0);
    comboDnsPriority->setFixedSize(160, 24);
    comboDnsPriority->setFont(labelFont);
    grid->addWidget(labelDnsPriority, row, 0, Qt::AlignLeft | Qt::AlignVCenter);
    grid->addWidget(comboDnsPriority, row++, 1, Qt::AlignLeft);
    // --- IP分组框 ---
    QGroupBox *groupIP = new QGroupBox("IP地址设置", this);
    groupIP->setFont(boldFont);
    groupIP->setStyleSheet("QGroupBox { border: 1px solid #A0A0A0; border-radius: 4px; margin-top: 6px; } QGroupBox::title { subcontrol-origin: margin; left: 10px; top: -6px; background: white; padding: 0 4px; }");
    groupIP->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    QVBoxLayout *ipVBox = new QVBoxLayout(groupIP);
    ipVBox->setContentsMargins(12, 12, 12, 12);
    ipVBox->setSpacing(10);
    ipVBox->addLayout(grid);
    groupIP->setLayout(ipVBox);
    mainLayout->addWidget(groupIP);
    mainLayout->addSpacing(16);

    // 验证选项和开机自动连接放在同一行
    QHBoxLayout *checkBoxLayout = new QHBoxLayout;
    checkValidate = new QCheckBox(tr("退出时验证设置(L)"), this);
    autoConnectCheckBox = new QCheckBox(tr("开机自动连接此网络"), this);
    // 设置统一字体
    QFont checkFont("Microsoft YaHei UI", 10);
    checkValidate->setFont(checkFont);
    autoConnectCheckBox->setFont(checkFont);
    checkValidate->setFixedHeight(24);
    autoConnectCheckBox->setFixedHeight(24);
    checkBoxLayout->addWidget(checkValidate);
    checkBoxLayout->addSpacing(32); // 两个复选框之间的间距
    checkBoxLayout->addWidget(autoConnectCheckBox);
    checkBoxLayout->addStretch();
    mainLayout->addLayout(checkBoxLayout);
    mainLayout->addSpacing(12);

    // 高级按钮
    QHBoxLayout *advLayout = new QHBoxLayout;
    advLayout->addStretch();
    btnAdvanced = new QPushButton("高级(V)...", this);
    btnAdvanced->setFixedSize(90, 23);
    btnAdvanced->setFont(labelFont);
    advLayout->addWidget(btnAdvanced);
    mainLayout->addLayout(advLayout);

    // 底部按钮区
    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->addStretch();
    btnOK = new QPushButton("确定", this);
    btnCancel = new QPushButton("取消", this);
    btnOK->setFixedSize(75, 28);
    btnCancel->setFixedSize(75, 28);
    btnOK->setFont(labelFont);
    btnCancel->setFont(labelFont);
    btnLayout->addWidget(btnOK);
    btnLayout->addWidget(btnCancel);
    mainLayout->addLayout(btnLayout);

    // 控件联动
    connect(radioAutoIP, &QRadioButton::toggled, [=](bool checked){
        editIP->setEnabled(!checked);
        editMask->setEnabled(!checked);
        editGW->setEnabled(!checked);
    });
    connect(radioAutoDNS, &QRadioButton::toggled, [=](bool checked){
        editDNS1->setEnabled(!checked);
        editDNS2->setEnabled(!checked);
    });
    connect(btnAdvanced, &QPushButton::clicked, this, [=]{
        AdvancedDialog dlg(this);
        QList<QPair<QString, int>> gwList;
        // 传递多网关
        if (!m_gatewayList.isEmpty()) {
            gwList = m_gatewayList;
        } else {
            QString gw = editGW->text().trimmed();
            if (!gw.isEmpty()) {
                gwList.append(qMakePair(gw, -1));
            }
        }
        if (radioAutoIP->isChecked()) {
            dlg.setIpMode(AdvancedDialog::DHCP);
            dlg.setGatewayList(gwList);
        } else {
            dlg.setIpMode(AdvancedDialog::Manual);
            dlg.setIpList(m_ipList.isEmpty() ? QList<QPair<QString, QString>>{qMakePair(editIP->text().trimmed(), editMask->text().trimmed())} : m_ipList);
            dlg.setGatewayList(gwList);
        }
        // 专业提示
        QLabel *tipLabel = new QLabel("专业提示：Linux下多网关主要用于冗余备份，负载均衡需用策略路由。普通用户无需配置多个网关。", &dlg);
        tipLabel->setStyleSheet("color:#888;font-size:10pt;margin-top:8px;");
        dlg.layout()->addWidget(tipLabel);
        if (dlg.exec() == QDialog::Accepted) {
            if (radioManualIP->isChecked()) {
                auto ipList = dlg.getIpList();
                if (!ipList.isEmpty()) {
                    editIP->setText(ipList[0].first);
                    editMask->setText(ipList[0].second);
                }
                auto gwList = dlg.getGatewayList();
                if (!gwList.isEmpty()) {
                    editGW->setText(gwList[0].first);
                } else {
                    editGW->setText("");
                }
                m_ipList = ipList;
                m_gatewayList = gwList;
            }
        }
    });
    connect(btnOK, &QPushButton::clicked, this, &IPv4PropertyDialog::onOkClicked);
    connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject);

    // 设置Tab顺序
    setTabOrder(radioAutoIP, radioManualIP);
    setTabOrder(radioManualIP, editIP);
    setTabOrder(editIP, editMask);
    setTabOrder(editMask, editGW);
    setTabOrder(editGW, radioAutoDNS);
    setTabOrder(radioAutoDNS, radioManualDNS);
    setTabOrder(radioManualDNS, editDNS1);
    setTabOrder(editDNS1, editDNS2);
    setTabOrder(editDNS2, checkValidate);
    setTabOrder(checkValidate, btnAdvanced);
    setTabOrder(btnAdvanced, btnOK);
    setTabOrder(btnOK, btnCancel);

    // 加载当前设置
    loadCurrentSettings();
}

void IPv4PropertyDialog::setValues(const QString &ip, const QString &mask, const QString &gw, const QString &dns1, const QString &dns2, bool validate) {
    if (ip.isEmpty() && mask.isEmpty() && gw.isEmpty()) {
        radioAutoIP->setChecked(true);
    } else {
        radioManualIP->setChecked(true);
    }
    editIP->setText(ip);
    editMask->setText(mask);
    editGW->setText(gw);
    if (dns1.isEmpty() && dns2.isEmpty()) {
        radioAutoDNS->setChecked(true);
    } else {
        radioManualDNS->setChecked(true);
    }
    editDNS1->setText(dns1);
    editDNS2->setText(dns2);
    checkValidate->setChecked(validate);
    // DNS优先级默认100
    comboDnsPriority->setCurrentIndex(0);
    // 清空多IP
    m_ipList.clear();
    if (!ip.isEmpty() && !mask.isEmpty()) {
        m_ipList.append(qMakePair(ip, mask));
    }
}

void IPv4PropertyDialog::getValues(QString &ip, QString &mask, QString &gw, QString &dns1, QString &dns2, bool &validate, bool &autoConnect, int &dnsPriorityLevel) const {
    if (radioManualIP->isChecked()) {
        ip = editIP->text();
        mask = editMask->text();
        gw = editGW->text();
    } else {
        ip.clear(); mask.clear(); gw.clear();
    }
    if (radioManualDNS->isChecked()) {
        dns1 = editDNS1->text();
        dns2 = editDNS2->text();
    } else {
        dns1.clear(); dns2.clear();
    }
    validate = checkValidate->isChecked();
    autoConnect = autoConnectCheckBox->isChecked();
    dnsPriorityLevel = comboDnsPriority->currentIndex();
    // 多IP由getIpList获取
}

void IPv4PropertyDialog::loadCurrentSettings() {
    // 获取连接名称
    QString connectionName = m_connInfo.name;
    if (connectionName.isEmpty()) {
        // 遍历所有profile名称，检查每个profile的connection.interface-name字段
        QProcess proc;
        proc.start("nmcli", QStringList() << "-t" << "-f" << "NAME" << "connection" << "show");
        proc.waitForFinished();
        QString output = proc.readAllStandardOutput();
        for (const QString &line : output.split('\n')) {
            QString profileName = line.trimmed();
            if (profileName.isEmpty()) continue;
            
            // 对每个profile检查其interface-name
            QProcess checkProc;
            checkProc.start("nmcli", QStringList() << "connection" << "show" << profileName);
            checkProc.waitForFinished();
            QString profileOutput = checkProc.readAllStandardOutput();
            
            for (const QString &profileLine : profileOutput.split('\n')) {
                QString trimmedProfileLine = profileLine.trimmed();
                if (trimmedProfileLine.startsWith("connection.interface-name:")) {
                    QString interfaceName = trimmedProfileLine.section(':', 1).trimmed();
                    if (interfaceName == m_devInfo.name) {
                        connectionName = profileName;
                        break;
                    }
                }
            }
            if (!connectionName.isEmpty()) break;
        }
    }
    
    if (connectionName.isEmpty()) {
        // 如果找不到连接名称，使用默认值
        radioAutoIP->setChecked(true);
        radioAutoDNS->setChecked(true);
        return;
    }
    
    // 获取连接详细信息
    QProcess proc;
    proc.start("nmcli", QStringList() << "connection" << "show" << connectionName);
    proc.waitForFinished();
    QString output = proc.readAllStandardOutput();
    
    QString ipv4Method = "auto";
    QString ipv4Address = "";
    QString ipv4Gateway = "";
    QStringList ipv4Dns;
    bool autoconnect = false;
    m_ipList.clear();
    m_gatewayList.clear();
    
    for (const QString &line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("ipv4.method:")) {
            ipv4Method = trimmedLine.section(':', 1).trimmed();
        } else if (trimmedLine.startsWith("ipv4.addresses")) {
            QString addrStr = trimmedLine.section(':', 1).trimmed();
            if (!addrStr.isEmpty()) {
                // 支持逗号分隔的多IP
                QStringList addrList = addrStr.split(',', Qt::SkipEmptyParts);
                for (const QString &addr : addrList) {
                QRegularExpression ipRegex(R"((\d+\.\d+\.\d+\.\d+)/(\d+))");
                    QRegularExpressionMatch match = ipRegex.match(addr.trimmed());
                if (match.hasMatch()) {
                        QString ip = match.captured(1);
                    int cidr = match.captured(2).toInt();
                        quint32 mask = (cidr >= 0 && cidr <= 32) ? ((0xFFFFFFFF << (32 - cidr)) & 0xFFFFFFFF) : 0;
                        QString netmask = QString("%1.%2.%3.%4")
                            .arg((mask >> 24) & 0xFF)
                            .arg((mask >> 16) & 0xFF)
                            .arg((mask >> 8) & 0xFF)
                            .arg(mask & 0xFF);
                        m_ipList.append(qMakePair(ip, netmask));
                    }
                }
                // 只用第一个IP显示在主界面
                if (!m_ipList.isEmpty()) {
                    ipv4Address = m_ipList[0].first;
                    editMask->setText(m_ipList[0].second);
                }
            }
        } else if (trimmedLine.startsWith("ipv4.gateway:")) {
            ipv4Gateway = trimmedLine.section(':', 1).trimmed();
        } else if (trimmedLine.startsWith("ipv4.dns")) {
            QString dns = trimmedLine.section(':', 1).trimmed();
            if (!dns.isEmpty()) {
                ipv4Dns.append(dns);
            }
        } else {
            // 用正则匹配 autoconnect 字段，兼容中英文冒号和空格
            QRegularExpression re("^connection\\.autoconnect[:：\\s]+(.+)$");
            QRegularExpressionMatch match = re.match(trimmedLine);
            if (match.hasMatch()) {
                QString val = match.captured(1).trimmed().toLower();
                autoconnect = (val == "yes" || val == "是" || val == "true" || val == "1");
            }
        }
    }
    
    // 设置IP配置
    if (ipv4Method == "auto") {
        radioAutoIP->setChecked(true);
        editIP->setText("");
        if (!ipv4Gateway.isEmpty()) {
            editGW->setText(ipv4Gateway);
        } else {
        editGW->setText("");
        }
    } else if (ipv4Method == "manual") {
        radioManualIP->setChecked(true);
        editIP->setText(ipv4Address);
        editGW->setText(ipv4Gateway);
    }
    
    // 设置DNS配置
    bool hasManualDNS = false;
    QRegularExpression ipRegex("^\\d{1,3}(\\.\\d{1,3}){3}$");
    QStringList allDns;
    for (const QString &dns : ipv4Dns) {
        QStringList dnsList = dns.split(QRegularExpression("[ ,;]+"), Qt::SkipEmptyParts);
        for (const QString &item : dnsList) {
            QString trimmed = item.trimmed();
            if (ipRegex.match(trimmed).hasMatch()) {
                hasManualDNS = true;
                break;
            }
        }
        allDns.append(dnsList);
        if (hasManualDNS) break;
    }
    if (hasManualDNS) {
        radioManualDNS->setChecked(true);
        QString dns1 = (allDns.value(0, "").trimmed() != "--") ? allDns.value(0, "") : "";
        QString dns2 = (allDns.value(1, "").trimmed() != "--") ? allDns.value(1, "") : "";
        editDNS1->setText(dns1);
        editDNS2->setText(dns2);
    } else {
        radioAutoDNS->setChecked(true);
        editDNS1->setText("");
        editDNS2->setText("");
    }
    
    // 设置autoconnect状态
    autoConnectCheckBox->setChecked(autoconnect);
    
    // 默认验证设置
    checkValidate->setChecked(true);
    
    // 读取dns-priority
    int dnsPriority = 100;
    for (const QString &line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("ipv4.dns-priority:")) {
            dnsPriority = trimmedLine.section(':', 1).trimmed().toInt();
        }
    }
    // 根据dnsPriority数值设置下拉框
    if (dnsPriority >= 150) comboDnsPriority->setCurrentIndex(0); // 高
    else if (dnsPriority >= 50) comboDnsPriority->setCurrentIndex(1); // 中
    else comboDnsPriority->setCurrentIndex(2); // 低
    
    // 初始化控件可用性
    editIP->setEnabled(!radioAutoIP->isChecked());
    editMask->setEnabled(!radioAutoIP->isChecked());
    editGW->setEnabled(!radioAutoIP->isChecked());
    editDNS1->setEnabled(!radioAutoDNS->isChecked());
    editDNS2->setEnabled(!radioAutoDNS->isChecked());
    // 设置DNS浮窗提示
    QStringList dnsShowList;
    for (const QString &dns : allDns) {
        if (!dns.trimmed().isEmpty() && dns.trimmed() != "--") dnsShowList << dns.trimmed();
    }
    
    // 如果当前是自动DNS模式，尝试获取系统当前的DNS地址
    if (dnsShowList.isEmpty() && radioAutoDNS->isChecked()) {
        QProcess proc;
        proc.start("cat", QStringList() << "/etc/resolv.conf");
        proc.waitForFinished();
        QString resolvOutput = proc.readAllStandardOutput();
        QRegularExpression dnsRegex("^nameserver\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");
        for (const QString &line : resolvOutput.split('\n')) {
            QRegularExpressionMatch match = dnsRegex.match(line.trimmed());
            if (match.hasMatch()) {
                dnsShowList << match.captured(1);
            }
        }
    }
    
    QString tip = dnsShowList.isEmpty() ? "当前无DNS地址" : ("当前已设置DNS：" + dnsShowList.join(", "));
    static_cast<DnsLineEdit*>(editDNS1)->dnsTip = tip;
    static_cast<DnsLineEdit*>(editDNS2)->dnsTip = tip;

    // 解析routes
    m_gatewayList.clear();
    if (!ipv4Gateway.isEmpty()) {
        m_gatewayList.append(qMakePair(ipv4Gateway, -1));
    }
    for (const QString &line : output.split('\n')) {
        QString trimmedLine = line.trimmed();
        if (trimmedLine.startsWith("ipv4.routes:")) {
            QString routesStr = trimmedLine.section(':', 1).trimmed();
            // 去除大括号和多余空格
            routesStr.replace("{", "");
            routesStr.replace("}", "");
            QStringList routeItems = routesStr.split(',', Qt::SkipEmptyParts);
            QString gw;
            int metric = -1;
            for (const QString &item : routeItems) {
                QString t = item.trimmed();
                // 解析nh和mt
                if (t.startsWith("nh = ")) {
                    gw = t.section('=', 1).trimmed();
                } else if (t.startsWith("mt = ")) {
                    metric = t.section('=', 1).trimmed().toInt();
                }
            }
            if (!gw.isEmpty() && gw != ipv4Gateway) {
                m_gatewayList.append(qMakePair(gw, metric));
            }
        }
    }
}

bool IPv4PropertyDialog::getAutoConnectStatus(const QString &connectionName) {
    if (connectionName.isEmpty()) return false;
    
    QProcess proc;
    proc.start("nmcli", QStringList() << "-g" << "connection.autoconnect" << "connection" << "show" << connectionName);
    proc.waitForFinished();
    QString output = proc.readAllStandardOutput().trimmed();
    return (output.toLower() == "yes" || output == "是");
}

QString IPv4PropertyDialog::findProfileNameByDevice(const QString &devName) {
    QProcess proc;
    proc.start("nmcli", QStringList() << "-t" << "-f" << "NAME" << "connection" << "show");
    proc.waitForFinished();
    QString output = proc.readAllStandardOutput();
    for (const QString &line : output.split('\n')) {
        QString profileName = line.trimmed();
        if (profileName.isEmpty()) continue;
        QProcess checkProc;
        checkProc.start("nmcli", QStringList() << "connection" << "show" << profileName);
        checkProc.waitForFinished();
        QString profileOutput = checkProc.readAllStandardOutput();
        for (const QString &profileLine : profileOutput.split('\n')) {
            QString trimmedProfileLine = profileLine.trimmed();
            if (trimmedProfileLine.startsWith("connection.interface-name:")) {
                QString interfaceName = trimmedProfileLine.section(':', 1).trimmed();
                if (interfaceName == devName) {
                    return profileName;
                }
            }
        }
    }
    return QString();
}

void IPv4PropertyDialog::onOkClicked() {
    // 只进行校验，不应用设置
    if (!validateSettings()) {
        return;
    }
    accept();
}

bool IPv4PropertyDialog::validateSettings() {
    // 如果选择手动IP，校验IP地址格式
    if (radioManualIP->isChecked()) {
        QString ip = editIP->text().trimmed();
        QString mask = editMask->text().trimmed();
        QString gateway = editGW->text().trimmed();
        QRegularExpression ipRegex("^\\d{1,3}(\\.\\d{1,3}){3}$");
        // 1. 校验子网掩码合法性
        if (!mask.isEmpty() && !isValidNetmask(mask)) {
            QMessageBox::warning(this, "子网掩码不合法", "请输入合法的子网掩码（如：255.255.255.0）");
            editMask->setFocus();
            return false;
        }
        // 2. 校验IP/网关为保留/广播/网络地址
        if (!ip.isEmpty() && (isReservedIP(ip) || isNetworkOrBroadcast(ip, mask))) {
            QMessageBox::warning(this, "IP地址非法", "IP地址为保留、网络或广播地址，请更换");
            editIP->setFocus();
            return false;
        }
        // 网关只校验保留地址
        if (!gateway.isEmpty() && isReservedIP(gateway)) {
            QMessageBox::warning(this, "网关地址非法", "网关地址为保留地址，请更换");
            editGW->setFocus();
            return false;
        }
        // 4. 校验网关和IP严格按掩码同网段，并判断网关可用性
        if (!ip.isEmpty() && !mask.isEmpty() && !gateway.isEmpty()) {
            QRegularExpression ipRegex("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$");
            QRegularExpressionMatch matchIP = ipRegex.match(ip);
            QRegularExpressionMatch matchGW = ipRegex.match(gateway);
            QRegularExpressionMatch matchMask = ipRegex.match(mask);
            if (!(matchIP.hasMatch() && matchGW.hasMatch() && matchMask.hasMatch())) {
                QMessageBox::warning(this, "网关冲突", "网关地址与IP地址不在同一网段，请检查设置");
                editGW->setFocus();
                return false;
            }
            quint32 ipVal = (matchIP.captured(1).toUInt() << 24) |
                             (matchIP.captured(2).toUInt() << 16) |
                             (matchIP.captured(3).toUInt() << 8) |
                             matchIP.captured(4).toUInt();
            quint32 gwVal = (matchGW.captured(1).toUInt() << 24) |
                             (matchGW.captured(2).toUInt() << 16) |
                             (matchGW.captured(3).toUInt() << 8) |
                             matchGW.captured(4).toUInt();
            quint32 maskVal = (matchMask.captured(1).toUInt() << 24) |
                               (matchMask.captured(2).toUInt() << 16) |
                               (matchMask.captured(3).toUInt() << 8) |
                               matchMask.captured(4).toUInt();
            quint32 net = ipVal & maskVal;
            quint32 broadcast = net | (~maskVal);
            // 计算掩码位数
            int maskBits = 0;
            quint32 tmp = maskVal;
            while (tmp & 0x80000000) { maskBits++; tmp <<= 1; }
            // 先判断网关和主机IP是否在同一网段
            if ((gwVal & maskVal) != (ipVal & maskVal)) {
                // 优化提示：只显示常用可用主机地址（去掉0和255结尾，排除网络和广播地址）
                int hostCount = 32 - maskBits;
                QStringList usableList;
                if (maskBits == 30) {
                    // /30 特殊处理
                    quint32 host1 = net + 1;
                    quint32 host2 = net + 2;
                    usableList << QString("%1.%2.%3.%4").arg((net >> 24) & 0xFF).arg((net >> 16) & 0xFF).arg((net >> 8) & 0xFF).arg(net & 0xFF)
                               << QString("%1.%2.%3.%4").arg((host1 >> 24) & 0xFF).arg((host1 >> 16) & 0xFF).arg((host1 >> 8) & 0xFF).arg(host1 & 0xFF)
                               << QString("%1.%2.%3.%4").arg((host2 >> 24) & 0xFF).arg((host2 >> 16) & 0xFF).arg((host2 >> 8) & 0xFF).arg(host2 & 0xFF);
                } else if (maskBits == 31) {
                    // /31 只有两个地址，通常点对点，理论上都可用
                    usableList << QString("%1.%2.%3.%4").arg((net >> 24) & 0xFF).arg((net >> 16) & 0xFF).arg((net >> 8) & 0xFF).arg(net & 0xFF)
                               << QString("%1.%2.%3.%4").arg((broadcast >> 24) & 0xFF).arg((broadcast >> 16) & 0xFF).arg((broadcast >> 8) & 0xFF).arg(broadcast & 0xFF);
                } else if (maskBits == 32) {
                    // /32 只有一个地址
                    usableList << QString("%1.%2.%3.%4").arg((net >> 24) & 0xFF).arg((net >> 16) & 0xFF).arg((net >> 8) & 0xFF).arg(net & 0xFF);
                } else {
                    quint32 first = net + 1;
                    quint32 last = broadcast - 1;
                    for (quint32 addr = first; addr <= last; ++addr) {
                        int lastByte = addr & 0xFF;
                        if (lastByte == 0 || lastByte == 255) continue; // 跳过0和255结尾
                        usableList << QString("%1.%2.%3.%4").arg((addr >> 24) & 0xFF).arg((addr >> 16) & 0xFF).arg((addr >> 8) & 0xFF).arg(addr & 0xFF);
                    }
                }
                QString rangeTip;
                if (usableList.isEmpty()) {
                    rangeTip = "无可用主机地址";
                } else if (usableList.size() == 1) {
                    rangeTip = usableList.first();
                } else if (usableList.size() <= 5) {
                    rangeTip = usableList.join("、");
                } else {
                    rangeTip = usableList.first() + " ~ " + usableList.last();
                }
                QMessageBox::warning(this, "网关冲突", QString("网关地址与IP地址不在同一网段，请检查设置\n常用可用主机地址范围：%1").arg(rangeTip));
                editGW->setFocus();
                return false;
            }
            // /30特殊处理
            if (maskBits == 30) {
                // 可用主机：net+1, net+2
                quint32 host1 = net + 1;
                quint32 host2 = net + 2;
                // 允许网关为net、host1、host2，但不能为broadcast
                if (gwVal == broadcast) {
                    QMessageBox::warning(this, "网关地址非法", "网关地址不能为广播地址，请更换");
                    editGW->setFocus();
                    return false;
                }
                if (!(gwVal == net || gwVal == host1 || gwVal == host2)) {
                    QString netStr = QString("%1.%2.%3.%4")
                        .arg((net >> 24) & 0xFF)
                        .arg((net >> 16) & 0xFF)
                        .arg((net >> 8) & 0xFF)
                        .arg(net & 0xFF);
                    QString host1Str = QString("%1.%2.%3.%4")
                        .arg((host1 >> 24) & 0xFF)
                        .arg((host1 >> 16) & 0xFF)
                        .arg((host1 >> 8) & 0xFF)
                        .arg(host1 & 0xFF);
                    QString host2Str = QString("%1.%2.%3.%4")
                        .arg((host2 >> 24) & 0xFF)
                        .arg((host2 >> 16) & 0xFF)
                        .arg((host2 >> 8) & 0xFF)
                        .arg(host2 & 0xFF);
                    QMessageBox::warning(this, "网关地址非法", QString("/30子网下，网关地址只能为：%1（网络地址）、%2、%3").arg(netStr).arg(host1Str).arg(host2Str));
                    editGW->setFocus();
                    return false;
                }
            } else {
                // 其它情况，网关不能为广播地址
                if (gwVal == broadcast) {
                    QMessageBox::warning(this, "网关地址非法", "网关地址不能为广播地址，请更换");
                    editGW->setFocus();
                    return false;
                }
            }
        }
    }
    
    // 如果选择手动DNS，校验DNS地址格式
    if (radioManualDNS->isChecked()) {
        QString dns1 = editDNS1->text().trimmed();
        QString dns2 = editDNS2->text().trimmed();
        
        QRegularExpression ipRegex("^\\d{1,3}(\\.\\d{1,3}){3}$");
        
        if (!dns1.isEmpty() && !ipRegex.match(dns1).hasMatch()) {
            QMessageBox::warning(this, "DNS地址格式错误", "请输入有效的首选DNS服务器地址");
            editDNS1->setFocus();
            return false;
        }
        
        if (!dns2.isEmpty() && !ipRegex.match(dns2).hasMatch()) {
            QMessageBox::warning(this, "DNS地址格式错误", "请输入有效的备用DNS服务器地址");
            editDNS2->setFocus();
            return false;
        }
    }
    
    return true;
}

bool IPv4PropertyDialog::isInSameSubnet(const QString &ip1, const QString &ip2, const QString &mask) {
    // 将IP地址和掩码转换为整数进行比较
    QRegularExpression ipRegex("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$");
    
    QRegularExpressionMatch match1 = ipRegex.match(ip1);
    QRegularExpressionMatch match2 = ipRegex.match(ip2);
    QRegularExpressionMatch matchMask = ipRegex.match(mask);
    
    if (!match1.hasMatch() || !match2.hasMatch() || !matchMask.hasMatch()) {
        return false;
    }
    
    // 计算IP地址的数值
    quint32 ip1Val = (match1.captured(1).toUInt() << 24) |
                     (match1.captured(2).toUInt() << 16) |
                     (match1.captured(3).toUInt() << 8) |
                     match1.captured(4).toUInt();
    
    quint32 ip2Val = (match2.captured(1).toUInt() << 24) |
                     (match2.captured(2).toUInt() << 16) |
                     (match2.captured(3).toUInt() << 8) |
                     match2.captured(4).toUInt();
    
    quint32 maskVal = (matchMask.captured(1).toUInt() << 24) |
                      (matchMask.captured(2).toUInt() << 16) |
                      (matchMask.captured(3).toUInt() << 8) |
                      matchMask.captured(4).toUInt();
    
    // 计算网络地址
    quint32 network1 = ip1Val & maskVal;
    quint32 network2 = ip2Val & maskVal;
    
    return network1 == network2;
} 

// 工具函数实现
bool IPv4PropertyDialog::isValidNetmask(const QString &mask) {
    // 转为32位整数，判断1是否连续
    QStringList parts = mask.split('.');
    if (parts.size() != 4) return false;
    quint32 val = 0;
    for (int i = 0; i < 4; ++i) {
        int n = parts[i].toInt();
        if (n < 0 || n > 255) return false;
        val = (val << 8) | n;
    }
    bool zero = false;
    for (int i = 31; i >= 0; --i) {
        if (val & (1 << i)) {
            if (zero) return false; // 1后面有0再有1
        } else {
            zero = true;
        }
    }
    return val != 0 && val != 0xFFFFFFFF;
}
bool IPv4PropertyDialog::isReservedIP(const QString &ip) {
    // 0.0.0.0, 127.0.0.1, 255.255.255.255, 224.0.0.0/4, 169.254.0.0/16
    QStringList parts = ip.split('.');
    if (parts.size() != 4) return true;
    int a = parts[0].toInt(), b = parts[1].toInt(), c = parts[2].toInt(), d = parts[3].toInt();
    if (ip == "0.0.0.0" || ip == "127.0.0.1" || ip == "255.255.255.255") return true;
    if (a >= 224 && a <= 239) return true;
    if (a == 169 && b == 254) return true;
    return false;
}
bool IPv4PropertyDialog::isNetworkOrBroadcast(const QString &ip, const QString &mask) {
    // 计算网络地址和广播地址
    QStringList ipParts = ip.split('.');
    QStringList maskParts = mask.split('.');
    if (ipParts.size() != 4 || maskParts.size() != 4) return false;
    quint32 ipVal = 0, maskVal = 0;
    for (int i = 0; i < 4; ++i) {
        ipVal = (ipVal << 8) | ipParts[i].toInt();
        maskVal = (maskVal << 8) | maskParts[i].toInt();
    }
    quint32 net = ipVal & maskVal;
    quint32 broadcast = net | (~maskVal);
    return (ipVal == net || ipVal == broadcast);
}

// 事件过滤器实现
bool IPv4PropertyDialog::eventFilter(QObject *obj, QEvent *event) {
    if (obj == editMask && event->type() == QEvent::FocusIn) {
        if (editMask->text().isEmpty()) {
            editMask->setText("255.255.255.0");
        }
    }
    return QDialog::eventFilter(obj, event);
} 

bool DnsLineEdit::eventFilter(QObject *obj, QEvent *event) {
    return QLineEdit::eventFilter(obj, event);
} 